package cn.yj.relay.core.controller;

import cn.yj.relay.common.exception.MyException;
import cn.yj.relay.common.token.AppAuthTokenHandler;
import cn.yj.relay.common.utils.StringUtils;
import cn.yj.relay.common.web.BaseController;
import cn.yj.relay.common.web.R;
import cn.yj.relay.core.entity.Admin;
import cn.yj.relay.core.entity.Emp;
import cn.yj.relay.core.service.IAdminService;
import cn.yj.relay.core.service.IEmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author 永健
 * @since 2020-03-04 10:43
 */
@RestController
public class LoginController extends BaseController
{

    @Autowired
    IEmpService iEmpService;


    @Autowired
    IAdminService iAdminService;


    /**
     * 登陆
     *
     * @param count
     * @param password
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestParam("count") String count, @RequestParam("password") String password)
    {
        String token = UUID.randomUUID().toString();
        Emp emp = iEmpService.login(count, password, token);
        Map map = getMap("token", token);
        if (StringUtils.isNotNull(emp))
        {
            map.put("name", emp.getName());
            map.put("role", "emp");
            AppAuthTokenHandler.saveUserRole(token, "emp");
            return success(map);
        }
        else
        {
            Admin admin = iAdminService.login(count, password, token);
            if (StringUtils.isNotNull(admin))
            {
                map.put("name", admin.getLoginName());
                map.put("role", "admin");
                AppAuthTokenHandler.saveUserRole(token, "admin");
                return success(map);
            }
        }
        throw new MyException("账号/密码错误");
    }


    /**
     * 退出登陆
     *
     * @return
     */
    @PostMapping("/logout")
    public R logout()
    {
        try
        {
            Emp loginEmp = getLoginEmp();
            loginEmp.setToken(UUID.randomUUID().toString());
            iEmpService.updateById(loginEmp);
        } catch (Exception e)
        {
            Admin admin = getLoginAdmin();
            admin.setToken(UUID.randomUUID().toString());
            iAdminService.updateById(admin);
        }
        return success();
    }

    @PostMapping("/admin/updaePwd")
    public R updadePwd(@RequestParam("oldPwd") String oldPwd, @RequestParam("pwd") String pwd)
    {
        Admin emp = getLoginAdmin();
        String password = emp.getPassword();
        if (!password.equals(oldPwd))
        {
            throw new MyException("就密码不对");
        }
        emp.setPassword(password);
        return result(iAdminService.saveOrUpdate(emp));
    }

}
